package james.gan.remoting.netty.pool;

import java.net.SocketAddress;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.pool2.impl.GenericObjectPool;

import james.gan.serialization.api.Serialization;

public class NettyClientPool {

	private static final ConcurrentHashMap<SocketAddress, NettyClientPool> clientPoolMap = new ConcurrentHashMap<>();

	private final GenericObjectPool<NettyClientProxy> pool;

	public NettyClientPool(SocketAddress socketAddress, Serialization serialization) {

		this.pool = new GenericObjectPool<NettyClientProxy>(new NettyClientFactory(socketAddress, serialization));
		this.pool.setTestOnBorrow(true);
		this.pool.setMaxTotal(2);
	}

	public static GenericObjectPool<NettyClientProxy> getWithSocketAddress(final SocketAddress address,
			final Serialization serialization) {
		NettyClientPool nettyClientPool = clientPoolMap.get(address);
		GenericObjectPool<NettyClientProxy> pool = Optional.ofNullable(nettyClientPool).orElseGet(() -> {
			synchronized (clientPoolMap) {
				NettyClientPool newPool = new NettyClientPool(address, serialization);
				clientPoolMap.put(address, newPool);
				return newPool;
			}
		}).pool;
		return pool;
	}
}
